package com.farm.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.farm.entity.User;
import com.farm.entity.UserRole;
import com.farm.service.UserService;

@Controller
public class AuthController {
    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private UserService userService;

    @GetMapping("/register")
    public String registerForm(Model model) {
        model.addAttribute("user", new User());
        return "register";
    }

    @PostMapping("/register")
    @ResponseBody
    public String register(@ModelAttribute User user) {
        try {
            logger.info("Attempting to register user: {}", user.getUsername());
            user.setRole(UserRole.FARMER);
            userService.registerUser(user);
            logger.info("Successfully registered user: {}", user.getUsername());
            return "注册成功，请等待管理员审核";
        } catch (Exception e) {
            logger.error("Error registering user: {}", user.getUsername(), e);
            return e.getMessage();
        }
    }

    @GetMapping("/login")
    public String loginForm() {
        return "login";
    }
} 